<?php

namespace library;

use GuzzleHttp\Client;
use support\Redis;

class wechat
{


    //获取微信小程序的openid
    public function get_openid($js_code)
    {
        $appid = env('WECHAT_APPID', '');
        $secret = env('WECHAT_SECRET', '');
        //改成
        //创建一个有基本URI的客户端
        $client = new Client();
        //发送请求
        $response = $client->request('GET', 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $js_code . '&grant_type=authorization_code');
        //获取返回数据
        $data = json_decode($response->getBody(), true);
        if (isset($data['openid'])) {
            return $data['openid'];
        }
        return $response;
    }


    //获取Access token
    public static function get_access_token()
    {
        if ($access_token = Redis::get('wechat_access_token')) {
            return $access_token;
        }

        $client = new Client();
        $url = 'https://api.weixin.qq.com/cgi-bin/token?appid=' . env('WECHAT_APPID') . '&secret=' . env('WECHAT_SECRET') . '&grant_type=client_credential';
        $res = $client->request('GET', $url);
        $data = json_decode($res->getBody(), true);
        if (isset($data['access_token'])) {
            Redis::set('wechat_access_token', $data['access_token'],'EX' ,7000);
        }
        return $data['access_token'] ?? null;
    }

}